/*-
 * #%L
 * rapidoid-web
 * %%
 * Copyright (C) 2014 - 2018 Nikolche Mihajlovski and contributors
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

package org.rapidoid.goodies;

import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.cls.Cls;
import org.rapidoid.commons.English;
import org.rapidoid.datamodel.IRange;
import org.rapidoid.datamodel.Range;
import org.rapidoid.gui.Btn;
import org.rapidoid.gui.GUI;
import org.rapidoid.gui.Grid;
import org.rapidoid.gui.Pager;
import org.rapidoid.gui.input.Form;
import org.rapidoid.http.ReqRespHandler;
import org.rapidoid.jdbc.JDBC;
import org.rapidoid.jpa.JPA;
import org.rapidoid.u.U;

import javax.persistence.metamodel.EntityType;
import java.util.List;
import java.util.Map;

@Authors("Nikolche Mihajlovski")
@Since("5.1.0")
public class X extends RapidoidThing {

	private static final Object OK = U.map();

	public static ReqRespHandler sql(final String sql, final Object... args) {
		return (ReqRespHandler) (req, resp) -> JDBC.query(sql, args);
	}

	public static ReqRespHandler jpql(final String jpql, final Object... args) {
		return (ReqRespHandler) (req, resp) -> {
			Map<String, Object> namedArgs = req != null ? req.data() : null;
			return JPA.jpql(jpql).bind(namedArgs).bind(args).all();
		};
	}

	public static ReqRespHandler index(final Class<?> entityType) {
		return (ReqRespHandler) (req, resp) -> JPA.of(entityType).all();
	}

	public static ReqRespHandler read(final Class<?> entityType) {
		return (ReqRespHandler) (req, resp) -> {
			Object id = Cls.convert(req.param("id"), idType(entityType));
			return JPA.get(entityType, id);
		};
	}

	public static ReqRespHandler insert(final Class<?> entityType) {
		return (ReqRespHandler) (req, resp) -> JPA.save(req.data(entityType));
	}

	public static ReqRespHandler update(final Class<?> entityType) {
		return (ReqRespHandler) (req, resp) -> {
			Object id = Cls.convert(req.param("id"), idType(entityType));
			JPA.get(entityType, id); // make sure it exists
			JPA.merge(req.data(entityType));  // FIXME improve the merge
			return OK;
		};
	}

	public static ReqRespHandler delete(final Class<?> entityType) {
		return (ReqRespHandler) (req, resp) -> {
			Object id = Cls.convert(req.param("id"), idType(entityType));
			JPA.delete(entityType, id);
			return OK;
		};
	}

	public static ReqRespHandler manage(final Class<?> entityType, final String baseUri) {
		return (ReqRespHandler) (req, resp) -> {
			if (resp.screen().title() == null) {
				resp.screen().title("Manage " + English.plural(name(entityType)));
			}

			long count = JPA.count(entityType);
			int pageSize = 10;
			int pages = (int) Math.ceil(count / (double) pageSize);
			int page = U.or(Cls.convert(req.params().get("page"), Integer.class), 1);

			IRange range = Range.of((page - 1) * pageSize, pageSize);
			List<?> records = JPA.of(entityType).page(range.start(), range.length());

			Grid grid = GUI.grid(records);

			Btn add = GUI.btn("Add " + name(entityType)).primary().go(baseUri + "/add");

			Pager pager = GUI.pager("page").min(1).max(pages).right(true);

			return GUI.multi(grid, GUI.div(pager, add));
		};
	}

	public static ReqRespHandler add(final Class<?> entityType, final String baseUri) {
		return (ReqRespHandler) (req, resp) -> {
			final Object entity = Cls.newInstance(entityType);

			if (resp.screen().title() == null) {
				resp.screen().title("Add " + name(entityType));
			}

			Btn save = btnSave(entity).go(baseUri + "/manage");
			Btn cancel = GUI.btn("Cancel").go(baseUri + "/manage");

			return GUI.create(entity).buttons(save, cancel);
		};
	}

	public static ReqRespHandler view(final Class<?> entityType, final String baseUri) {
		final Class<?> idType = idType(entityType);

		return (ReqRespHandler) (req, resp) -> {

			final Object id = Cls.convert(req.param("id"), idType);
			final Object entity = JPA.getIfExists(entityType, id);

			if (entity == null) {
				return null;
			}

			JPA.detach(entity);

			String name = name(entityType);

			if (resp.screen().title() == null) {
				resp.screen().title(name + " Details");
			}

			final Btn edit = GUI.btn("Edit").go(uri(baseUri, entity) + "/edit");

			Btn all = GUI.btn("View all").go(baseUri + "/manage");

			Btn del = btnDelete().go(baseUri + "/manage").onClick(() -> JPA.delete(entityType, id)).confirm("Do you really want to delete the " + name + "?");

			Form form = GUI.show(entity).buttons(edit, all, del).visible(!del.clicked());

			Object msg = del.clicked() ? GUI.div("The data was deleted.") : "";

			return GUI.multi(form, msg);
		};
	}

	public static ReqRespHandler edit(final Class<?> entityType, final String baseUri) {
		return (ReqRespHandler) (req, resp) -> {

			Object id = Cls.convert(req.param("id"), idType(entityType));
			Object entity = JPA.getIfExists(entityType, id);

			if (entity == null) {
				return null;
			}

			JPA.detach(entity);

			if (resp.screen().title() == null) {
				resp.screen().title("Edit " + name(entityType));
			}

			Btn save = btnSave(entity).go(baseUri + "/manage");
			Btn cancel = GUI.btn("Cancel").go(uri(baseUri, entity) + "/view");

			return GUI.edit(entity).buttons(save, cancel);
		};
	}

	public static Btn btnSave(final Object entity) {
		return GUI.btn("Save").primary().onSuccess(() -> JPA.save(entity));
	}

	public static Btn btnDelete() {
		return GUI.btn("Delete").danger().confirm("Do you really want to delete the data?");
	}

	private static String name(Class<?> entityType) {
		return entityType.getSimpleName();
	}

	private static Class<?> idType(Class<?> entityType) {
		for (EntityType<?> t : JPA.getEntityTypes()) {
			if (t.getJavaType().equals(entityType)) {
				return t.getIdType() != null ? t.getIdType().getJavaType() : null;
			}
		}

		return null;
	}

	public static String uri(String baseUri, Object entity) {
		return GUI.uriFor(baseUri, entity);
	}

	public static ScaffoldDSL scaffold(Class<?> entityType) {
		return new ScaffoldDSL(entityType);
	}

}
